package org.ling.xuan.action;

import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.ling.xuan.condition.LxCondition;
import org.ling.xuan.dao.FileDao;
import org.ling.xuan.dao.ProjectDao;
import org.ling.xuan.entity.HundSonInfo;
import org.ling.xuan.entity.mo.CommonSetting;
import org.ling.xuan.entity.mo.ProjectSetting;
import org.ling.xuan.util.LxOptional;
import org.ling.xuan.util.LxStrUtil;

/**
 * 获取注释区域修改信息 自动插入鼠标光标处 // [修改信息] beg
 *
 * @author liting50684
 * @date 2023/08/21
 */
public class LxAnnotationInsertBegAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        String filePath = LxOptional.of(e, c -> c.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE).getPath()).orElse("");
        Editor editor = e.getDataContext().getData(com.intellij.openapi.actionSystem.PlatformDataKeys.EDITOR);
        String basePath = LxOptional.of(e, c -> c.getProject().getBasePath()).orElse("");
        if (project != null && editor != null && StrUtil.isNotBlank(filePath)) {
            LxStrUtil.unionPath(filePath);
            LxStrUtil.unionPath(basePath);
            CommonSetting commonSetting = FileDao.get(CommonSetting.class, "CommonSetting.json", new CommonSetting());
            ProjectSetting projectSetting = ProjectDao.getSetting(basePath);
            HundSonInfo hundSonInfo = new HundSonInfo(filePath, projectSetting.getSystemName(), commonSetting.getAuth());
            if (StrUtil.isNotBlank(hundSonInfo.getLastAnnotationContent())) {
                WriteCommandAction.runWriteCommandAction(project, () -> {
                    FileDocumentManager.getInstance().saveDocument(editor.getDocument());
                    CaretModel caretModel = editor.getCaretModel();
                    int offset = caretModel.getOffset();
                    editor.getDocument().insertString(offset, "//" + hundSonInfo.getLastAnnotationContent() + " beg");
                    FileDocumentManager.getInstance().saveDocument(editor.getDocument());
                });
            }
        }
    }

    @Override
    public void update(AnActionEvent e) {
        boolean enable = LxCondition.getInstance().canAnnotationDeal(e);
        e.getPresentation().setEnabledAndVisible(enable);
    }
}
